package cn.sunline.dreamvalue.utils;

import cn.sunline.dreamvalue.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 11292
 * @title: DreamValuNoGenerateUtil
 * @projectName dream-value
 * @description: 梦想值账号生成器
 * @date 2020/5/723:37
 */
@Component
public class DreamValueNoGenerateUtil {

    @Autowired
    private RedisOpsUtil redisOpsUtil;

    /**
     　* @description: 生成20位的梦想账号
       * 渠道来源（3位翻转）+生成日期（8位）+ 自增序列（9位）
     　* @param [sourceType]
     　* @return java.lang.String
     　* @author 11292
     　* @date 2020/5/7 23:41
     */
    public String generateDreamValueNo(String sourceType) {

        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = RedisConstant.DREAM_VALUE_NO_GENERATE_REIDS_KEY_PRIFIX + date + ":" + sourceType;
        Long increment = redisOpsUtil.incr(key, 1);
        if(increment == 1){
            redisOpsUtil.expire(key,60*60*24, TimeUnit.SECONDS);
        }
        sb.append(sourceType);
        sb = sb.reverse();
        sb.append(date);
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 9) {
            sb.append(String.format("%09d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     　* @description: 生成20位的梦想值流水号
        * 生成日期（8位）+操作类型（2位）+ 自增序列（10位）
     　* @param []
     　* @return java.lang.String
     　* @author 11292
     　* @date 2020/5/7 23:41
     */
    public String generateDreamValueFlowNo(String opType) {

        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = RedisConstant.DREAM_VALUE_FLOWNO_GENERATE_REIDS_KEY_PRIFIX + date + ":" + opType;
        Long increment = redisOpsUtil.incr(key, 1);
        if(increment == 1){
            redisOpsUtil.expire(key,60*60*24, TimeUnit.SECONDS);
        }
        sb.append(date);
        sb.append(opType);
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 10) {
            sb.append(String.format("%010d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }
}
